<template>
	<view class="chat">
		<view class="scroll-view">
			<view class="all-history-loaded">
				{{allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息'}}
			</view>
			<!--已经收到的消息-->
			<view v-for="(message,index) in messages" :key="message.messageId">
				<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
				<view class="time-lag">
					{{renderMessageDate(message,index)}}
				</view>
				<view class="message-item" :class="message.senderId == currentUser.userId ? 'self':''">
					<view class="avatar" v-if="message.senderId != currentUser.userId">
						<image :src="ip+'/img/'+friend.avatar" mode=""></image>
					</view>
					<view class="avatar" v-else>
						<image :src="ip+'/img/'+currentUser.avatar" mode=""></image>
					</view>
					<view class="content" v-if="message.type == 'text'" v-html="renderTextMessage(message)"></view>
				</view>
			</view>
		</view>

		</scroll-view>
		<view class="input">
			<view class="input-box">
				<text class="iconfont icon-douyin icon-input-douyin"></text>
				<input type="text" v-model="content" class="input-content" focus="ture" placeholder="发送消息" />
				<text v-show="message!=0" @click="sendTextMessage"
					class="iconfont icon-arrowTop-fill icon-input-send"></text>
			</view>
		</view>
	</view>
</template>

<script>
	import t from '../../common/helper.js';
	import EmojiDecoder from "../../lib/EmojiDecoder.js";
	import {
		mapState
	} from 'vuex';
	let vm;
	export default {
		computed: {
			...mapState(['new_total']) //新消息
		},
		data() {
			let emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
			let emojiMap = {
				'[么么哒]': 'emoji_3@2x.png',
				'[乒乓]': 'emoji_4@2x.png',
				'[便便]': 'emoji_5@2x.png',
				'[信封]': 'emoji_6@2x.png',
				'[偷笑]': 'emoji_7@2x.png',
				'[傲慢]': 'emoji_8@2x.png'
			};
			return {
				ip: t.o,
				//聊天文本框
				content: '',
				//已经接收到的消息
				messages: [],
				currentUser: '',
				friend: '',
				id: '',
				//定义表情列表
				emoji: {
					url: emojiUrl,
					map: emojiMap,
					show: false,
					decoder: new EmojiDecoder(emojiUrl, emojiMap),
				},
				//已经加载完所有历史消息
				allHistoryLoaded: false,
				currentUser: '',
			}
		},
		async onLoad(options) {
			vm = this;
			this.currentUser = uni.getStorageSync('user')[0];
			this.id = this.currentUser.userId;
			let imService = getApp().globalData.imService;
			//聊天对象
			let friendId = options.id;
			//从服务器获取最新的好友信息
			await this.initfriend(friendId);
			this.messages = imService.getPrivateMessages(friendId);
			if(this.messages.length == 0) {
				this.firstLoad()
			}
			//监听新消息
			imService.onNewPrivateMessageReceive = (friendId, message) => {
				if (friendId === this.friend.userId) {
					//聊天时，收到消息标记为已读
					this.markPrivateMessageAsRead(friendId);
					//收到新消息，是滚动到最底部
					this.scrollToBottom();
				}
			};
			//每次进入聊天页面，总是滚动到底部
			this.scrollToBottom();
			//收到的消息设置为已读
			if (this.messages.length !== 0) {
				this.markPrivateMessageAsRead(friendId);
				this.messages.forEach(item => {
					if (item.senderId != this.currentUser.userId) {
						this.$store.commit('changeNew', this.messages.length);
					}
				})
			}
		},
		onPullDownRefresh(e) {
			this.loadMoreHistoryMessage();
		},
		onUnload() {
			//退出聊天页面之前，清空页面传入的监听器
			let imService = getApp().globalData.imService;
			if (imService) {
				imService.onNewPrivateMessageReceive = (friendId, message) => {};
			}
		},
		methods: {
			//返回上一页
			back() {
				uni.navigateBack({
					delta: 2
				})
			},
			//渲染文本消息，如果包含表情，替换为图片
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderTextMessage(message) {
				return '<span class="text-content">' + this.emoji.decoder.decode(message.payload.text) + '</span>'
			},
			//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderMessageDate(message, index) {
				if (index === 0) {
					return this.formatDate(message.timestamp)
				} else {
					if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
						return this.formatDate(message.timestamp)
					}
				}
				return '';
			},
			sendMessage(message) {
				let toId = message.to.id;
				let imService = getApp().globalData.imService;
				let localHistory = imService.getPrivateMessages(toId);
				localHistory.push(message);
				this.goEasy.im.sendMessage({
					message: message,
					onSuccess: function(message) {
						console.log("发送成功.", message);
					},
					onFailed: function(error) {
						console.log("发送失败:", error);
					}
				});
			},
			sendTextMessage() { //发送消息
				if (this.content.trim() !== '') {
					let body = this.content;
					if (this.content.length >= 50) {
						body = this.content.substring(0, 30) + "...";
					}
					let textMessage = this.goEasy.im.createTextMessage({
						text: this.content,
						to: {
							id: this.friend.userId,
							type: this.GoEasy.IM_SCENE.PRIVATE,
							data: {
								name: this.friend.userName,
								avatar: this.friend.avatar
							}
						},
						notification: {
							title: this.currentUser.userName + '发来一段文字',
							body: body
						}
					});
					this.sendMessage(textMessage);
				}
				this.scrollToBottom();
				this.content = "";
			},

			//从服务器获取最新的好友信息
			getFriend: (friendId) => {
				return new Promise((resolve, reject) => {
					uni.request({
						url: `${t.o}/user`,
						method: 'POST',
						data: {
							id: friendId
						},
						success: res => {
							vm.friend = res.data.data[0];
							//设置导航栏信息
							uni.setNavigationBarTitle({
								title: vm.friend.userName
							});
							resolve();
						}
					})
				})
			},
			async initfriend(friendId) {
				await this.getFriend(friendId);
			},
			//回滚底部
			scrollToBottom() {
				this.$nextTick(function() {
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration: 10
					})
				});
			},
			
			firstLoad() {
				let self = this;
				let lastMessageTimeStamp = Date.now();
				let currentLength = this.messages.length;
				this.goEasy.im.history({
					userId: self.friend.userId,
					lastTimestamp: lastMessageTimeStamp,
					onSuccess: function(result) {
						//获取本地记录
						let imService = getApp().globalData.imService;
						let localHistory = imService.getPrivateMessages(self.friend.userId);
						//添加加载的记录到本地记录尾部
						let messages = result.content;
						for (let i = messages.length - 1; i >= 0; i--) {
							if(lastMessageTimeStamp-messages[i].timestamp < 24 * 60 * 60 * 1000){
								
							}
							// if(currentLength - self.formatDate(messages[i].payload.timestamp))
							// localHistory.unshift(messages[i]);
						}
					
						// if (localHistory.length === currentLength) {
						// 	self.allHistoryLoaded = true;
						// }
						// self.messages = localHistory;
						// uni.stopPullDownRefresh();
					},
					onFailed: function(error) {
						//获取失败
						if (error.code === 401) {
							console.log("获取历史消息失败,默认不开通，付费应用，可以在我的应用->查看详情，高级功能里自助开通");
						} else {
							console.log("获取历史消息失败, code:" + error.code + ",错误信息:" + error.content);
						}
						uni.stopPullDownRefresh();
					}
				})
			},
			
			
			//历史消息
			loadMoreHistoryMessage() { //历史消息
				let self = this;
				let lastMessageTimeStamp = Date.now();
				let lastMessage = this.messages[0];
				if (lastMessage) {
					lastMessageTimeStamp = lastMessage.timestamp;
				}
				let currentLength = this.messages.length;
				this.goEasy.im.history({
					userId: self.friend.userId,
					lastTimestamp: lastMessageTimeStamp,
					onSuccess: function(result) {
						//获取本地记录
						let imService = getApp().globalData.imService;
						let localHistory = imService.getPrivateMessages(self.friend.userId);
						//添加加载的记录到本地记录尾部
						let messages = result.content;
						console.log(messages)
						for (let i = messages.length - 1; i >= 0; i--) {
							localHistory.unshift(messages[i]);
						}

						if (localHistory.length === currentLength) {
							self.allHistoryLoaded = true;
						}
						self.messages = localHistory;
						uni.stopPullDownRefresh();
					},
					onFailed: function(error) {
						//获取失败
						if (error.code === 401) {
							console.log("获取历史消息失败,默认不开通，付费应用，可以在我的应用->查看详情，高级功能里自助开通");
						} else {
							console.log("获取历史消息失败, code:" + error.code + ",错误信息:" + error.content);
						}
						uni.stopPullDownRefresh();
					}
				});
			},
			//标为已读
			markPrivateMessageAsRead(friendId) {
				this.goEasy.im.markPrivateMessageAsRead({
					userId: friendId,
					onSuccess: function() {
						console.log('标记为已读成功');
						//vuex改变已读信息状态
						// this.$store.commit('saveNew')
					},
					onFailed: function(error) {
						console.log(error);
					}
				});
			}

		}
	}
</script>

<style lang="scss">
	.chat {
		overflow: hidden;
		position: relative;

		&::before {
			content: '';
			position: absolute;
			width: 100%;
			height: 1px;
			background-color: #FFFFFF;
			transform: translateY(-0.9px);
		}

		.scroll-view {
			padding: 0 10px 90px;
			box-sizing: border-box;
			-webkit-overflow-scrolling: touch;

			.all-history-loaded {
				color: #878787;
				font-size: 12px;
				text-align: center;
				line-height: 12px;
				margin: 20px auto;
			}

			.time-lag {
				font-size: 10px;
				line-height: 16px;
				text-align: center;
			}

			.self {
				flex-direction: row-reverse;

				.avatar {
					margin-left: 10px;
					margin-right: 0;
				}
			}

			.message-item {
				display: flex;
				align-items: center;
				padding: 5px 0;
				box-sizing: border-box;

				.avatar {
					width: 40px;
					height: 40px;
					border-radius: 50%;
					margin-right: 10px;

					image {
						width: 100%;
						height: 100%;
						border-radius: 50%;
					}
				}

				.content {
					max-width: 200px;
					padding: 10px;
					white-space: pre-wrap;
					word-break: break-all;
					word-wrap: break-word;
					border-radius: 10px;
					line-height: 24px;
					font-size: 16px;
					background: #618DFF;
					color: #ffffff;
					box-sizing: border-box;
				}
			}
		}

		.input {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 90px;
			padding: 10px 10px 40px;
			box-sizing: border-box;
			background-color: #000000;
			z-index: 999;

			.input-box {
				width: 100%;
				height: 100%;
				background-color: #252525;
				border-radius: 20px;
				display: flex;
				align-items: center;
				padding: 5px;
				box-sizing: border-box;

				.icon-input-douyin,
				.icon-input-send {
					background-color: #0055ff;
					font-size: 20px;
					border-radius: 50%;
					padding: 5px;
					box-sizing: border-box;
				}

				.icon-input-send {
					background-color: #ff0055;
				}

				.input-content {
					flex: 0 0 80%;
					margin-left: 10px;
				}
			}
		}
	}
</style>
